package com.example.mykotlin.base.flex

import com.example.mykotlin.base.util.Constant
import com.example.mykotlin.base.util.tryOnly
import com.mybatisflex.annotation.InsertListener
import com.mybatisflex.annotation.UpdateListener
import java.lang.reflect.Field
import java.time.LocalDateTime
import java.util.Date

class MyInsertUpdateListener : InsertListener, UpdateListener {
    companion object {
        const val CREATE_TIME = "createTime"
        const val UPDATE_TIME = "updateTime"
    }

    override fun onInsert(entity: Any) {
        val ldtNow = LocalDateTime.now()
        val dateNow = Date()
        val time = System.currentTimeMillis()
        setTime(entity, CREATE_TIME, ldtNow, dateNow, time)
        setTime(entity, UPDATE_TIME, ldtNow, dateNow, time)
    }

    override fun onUpdate(entity: Any) {
        setTime(entity, UPDATE_TIME)
    }

    private fun setTime(
        entity: Any, fieldName: String,
        ldtNow: LocalDateTime = LocalDateTime.now(),
        dateNow: Date = Date(),
        time: Long = System.currentTimeMillis(),
    ) {
        tryOnly {
            val clazz = entity::class.java
            val field: Field = clazz.getDeclaredField(fieldName)
            field.setAccessible(true)
            val type = field.type
            when (type) {
                Date::class.java -> field.set(entity, dateNow)
                String::class.java -> field.set(entity, ldtNow.format(Constant.DTF))
                Long::class.java -> field.set(entity, time)
                else -> field.set(entity, ldtNow)
            }
        }
    }


}